package service

import (
	"errors"
	"fmt"
	"gin-wave-im/global"
	"gin-wave-im/model"
	"gin-wave-im/util"
	"log"
)

// 添加消息
func AddMessage(msg *model.Message) (id uint64, err error) {
	picLen := len(msg.Pic)
	if picLen > 0 {
		hostLen := len(global.GnConfig.System.ImgHost)
		msg.Pic = msg.Pic[hostLen:]
		msg.ThumbPic = msg.ThumbPic[hostLen:]
	}
	err = global.GnDb.Create(&msg).Error
	if err != nil {
		return 0,errors.New("数据库错误！")
	}

	if msg.Cmd == model.CMD_SINGLE_MSG {
		// 用户最新消息有序集合msg#userId
		userKey := fmt.Sprintf("%s%d", global.GnRedisKey.Message.UserNewMsgKey, msg.UserId)
		global.GnRedis.Do("zAdd", userKey, msg.ID, msg.DstId)
		dstKey := fmt.Sprintf("%s%d", global.GnRedisKey.Message.UserNewMsgKey, msg.DstId)
		global.GnRedis.Do("zAdd", dstKey, msg.ID, msg.UserId)
	} else if msg.Cmd == model.CMD_ROOM_MSG {
		// 群最新消息有序集合msg#communitiyId
		key := fmt.Sprintf("%s%d", global.GnRedisKey.Message.GroupNewMsgKey, msg.DstId)
		global.GnRedis.Do("zAdd", key, msg.ID, msg.UserId)
	}

	return id,nil
}

// 获得历史消息
func HistoryRecord(userId uint64, dstId uint64, cmd uint8, page int) (messages []model.Message, err error) {
	pageSize := 20
	offset := (page - 1) * pageSize
	messages = []model.Message{}
	if cmd == model.CMD_SINGLE_MSG {
		sql := fmt.Sprintf("SELECT * FROM messages WHERE ((user_id=%d AND dst_id=%d) OR (user_id=%d AND dst_id=%d)) AND cmd=%d ORDER BY created_at DESC LIMIT %d,%d", userId, dstId, dstId, userId, cmd, offset, pageSize)
		err = global.GnDb.Raw(sql).Scan(&messages).Error
	} else {
		err = global.GnDb.Where("dst_id = ?", dstId).Where("cmd = ?", cmd).Order("created_at desc").Find(&messages).Error
	}

	for i, msg := range messages{
		if msg.ThumbPic != "" {
			messages[i].ThumbPic = util.TransformImageUrl(msg.ThumbPic)
			messages[i].Pic = util.TransformImageUrl(msg.Pic)
		}
	}

	return messages,err
}

// 消息设为已读
func MakeRead(userId uint64, dstId uint64, cmd uint8) error {
	err := global.GnDb.Model(&model.Message{}).Where("user_id = ?", userId).Where("dst_id = ?", dstId).Where("cmd = ?", cmd).Update("read", 1).Error
	return err
}

// 获得实时最新消息
func RealTimeMessage(userId uint64) ([]model.Message, error) {
	msgIds := []uint64{}
	comIds, comErr := SearchCommunityIds(userId)
	if comErr == nil {
		for _, v := range comIds {
			groupKey := fmt.Sprintf("%s%d", global.GnRedisKey.Message.GroupNewMsgKey, v)
			gRes,gErr := global.GnRedis.ZRevRangeWithScores(groupKey, 0, -1).Result()
			if gErr == nil {
				for _,msg := range gRes{
					msgIds = append(msgIds, uint64(msg.Score))
				}
			}
		}
	}
	userKey := fmt.Sprintf("%s%d", global.GnRedisKey.Message.UserNewMsgKey, userId)
	//global.GN_REDIS.Del(userKey)
	res,err := global.GnRedis.ZRevRangeWithScores(userKey, 0, -1).Result()
	messages := []model.Message{}
	if err != nil {
		return nil, err
	}
	for _,msg := range res {
		msgIds = append(msgIds, uint64(msg.Score))
	}
	log.Println(msgIds)
	for _,msgId := range msgIds {
		tmp,_err := MsgInfo(msgId)
		if tmp.Cmd == model.CMD_SINGLE_MSG {
			if tmp.UserId != userId {
				tmp.DstId = tmp.UserId
				tmp.UserId = userId
				//userUuid := tmp.DstUuid
				//tmp.DstUuid = tmp.UserUuid
				//tmp.UserUuid = userUuid
			}
		} else if tmp.Cmd == model.CMD_ROOM_MSG {
			tmp.UserId = userId
		}
		if _err == nil {
			flag := true
			for _,msg := range messages {
				if tmp.Cmd == msg.Cmd && tmp.DstId == msg.DstId {
					flag = false
				}
			}
			if flag {
				messages = append(messages, tmp)
			}
		}
	}

	return messages,err
}

// 消息信息
func MsgInfo(id uint64) (model.Message, error) {
	msg := model.Message{}
	err := global.GnDb.First(&msg, id).Error

	return msg,err
}